package com.yswy.backstage.serviceApi.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yswy.backstage.dto.api.AppEventCallback;
import com.yswy.backstage.dto.api.TgCallBackIdReids;
import com.yswy.backstage.dto.api.UserDeviceInfo;
import com.yswy.backstage.service.*;
import com.yswy.backstage.serviceApi.ApiTgCallBackJlIdService;
import com.yswy.backstage.serviceApi.ApiTgCallBackKsIdService;
import com.yswy.backstage.serviceApi.ApiTgCallBackLoglService;
import com.yswy.backstage.serviceApi.ApiTgChannelService;
import com.yswy.backstage.utils.BackStringUtils;
import com.yswy.common.enums.DateUnitEnums;
import com.yswy.common.enums.TfPlatformEnums;
import com.yswy.common.enums.TriggerNodeEnums;
import com.yswy.common.utils.DateUtils;
import com.yswy.common.utils.StringUtils;
import com.yswy.common.utils.redis.RedisConstants;
import com.yswy.common.utils.redis.RedisUtil;
import com.yswy.common.zfbOrder.AgreementStatusEnums;
import com.yswy.domain.entity.PackageManage;
import com.yswy.domain.entity.tf.*;
import com.yswy.domain.mapper.tf.TgCallBackDelayedMapper;
import com.yswy.domain.mapper.tf.TgCallBackLogMapper;
import io.swagger.annotations.ApiModelProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
public class ApiTgCallBackLogServiceImpl extends ServiceImpl<TgCallBackLogMapper, TgCallBackLog>
        implements ApiTgCallBackLoglService {
    @Autowired
    private  RedisUtil redisUtil ;
    @Autowired
    private  ApiTgChannelService apiTgChannelService ;
    @Autowired
    private  TgEventService tgEventService ;
    @Autowired
    private  TgEventEnumsService tgEventEnumsService ;
    @Autowired
    private  ApiTgCallBackJlIdService apiTgCallBackJlIdService ;
    @Autowired
    private  ApiTgCallBackKsIdService apiTgCallBackKsIdService ;

    @Autowired
    private TgCallBackDelayedMapper tgCallBackDelayedMapper ;

    @Override
    public TgCallBackIdReids getUserSource(AppEventCallback appEventCallback) {
        String oaidCache_jlyq = null;
        String ipCache_jlyq = null;
        String oaidCache_clzt = null;
        String ipCache_clzt = null;
        UserDeviceInfo userDeviceInfo = appEventCallback.getUserDeviceInfo();
        if (StringUtils.isNotEmpty(userDeviceInfo.getOaid())){
            oaidCache_jlyq = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_oaid_jlyq
                    ,userDeviceInfo.getOaid() ,appEventCallback.getChannel() , appEventCallback.getProjectId()
                    ,  appEventCallback.getTriggerNode());
            oaidCache_clzt = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_oaid_clzt
                    ,userDeviceInfo.getOaid() ,appEventCallback.getChannel() , appEventCallback.getProjectId()
                    ,  appEventCallback.getTriggerNode());

        }
        if (StringUtils.isNotEmpty(userDeviceInfo.getIp())){
            ipCache_jlyq = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_ip_jlyq
                    ,userDeviceInfo.getIp() ,appEventCallback.getChannel() , appEventCallback.getProjectId()
                    ,  appEventCallback.getTriggerNode());
            ipCache_clzt = BackStringUtils.getTgCallbackKey(RedisConstants.cacheTgBack_ip_jlyq
                    ,userDeviceInfo.getIp() ,appEventCallback.getChannel() , appEventCallback.getProjectId()
                    ,  appEventCallback.getTriggerNode());

        }

        Boolean oaidCache_jlyq_boolean = redisUtil.hasKey(oaidCache_jlyq) ;
        Boolean ipCache_jlyq_boolean = redisUtil.hasKey(ipCache_jlyq) ;
        Boolean oaidCache_clzt_boolean = redisUtil.hasKey(oaidCache_clzt) ;
        Boolean ipCache_clzt_boolean = redisUtil.hasKey(ipCache_clzt) ;

        TgCallBackIdReids tgCallBackIdReids = null ;
        if (oaidCache_jlyq_boolean || ipCache_jlyq_boolean){
            TgCallBackJlId tgCallBackJlId  = null ;
            printlnLog("识别为：巨量引擎平台" ,appEventCallback);
            if (oaidCache_jlyq_boolean){
                tgCallBackJlId = (TgCallBackJlId)redisUtil.getObejct(oaidCache_jlyq);
            }else if (ipCache_jlyq_boolean){
                tgCallBackJlId = (TgCallBackJlId)redisUtil.getObejct(ipCache_jlyq);
            }
            tgCallBackIdReids = new TgCallBackIdReids(TfPlatformEnums.JLYQ.toString(),tgCallBackJlId  , oaidCache_jlyq ,ipCache_jlyq );
        }
        if (oaidCache_clzt_boolean || ipCache_clzt_boolean){
            printlnLog("识别为：磁力智投平台" ,appEventCallback);
            TgCallBackKsId tgCallBackKsId  = null ;
            if (oaidCache_jlyq_boolean){
                tgCallBackKsId = (TgCallBackKsId)redisUtil.getObejct(oaidCache_jlyq);
            }else if (ipCache_jlyq_boolean){
                tgCallBackKsId = (TgCallBackKsId)redisUtil.getObejct(ipCache_jlyq);
            }
            tgCallBackIdReids = new TgCallBackIdReids(TfPlatformEnums.CLZT.toString(),tgCallBackKsId  , oaidCache_jlyq ,ipCache_jlyq );
        }
        return tgCallBackIdReids;
    }
    @Override
    public void callbackAppTriggerNode(AppEventCallback appEventCallback) {
        TgCallBackIdReids tgCallBackIdReids =  getUserSource(appEventCallback);
        if (tgCallBackIdReids == null){
            printlnLog("识别为：未匹配到平台" ,appEventCallback);
            return;
        }
        TgChannel tgChannel = null ;
        if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.JLYQ.toString())){
            TgCallBackJlId tgCallBackJlId = tgCallBackIdReids.getTgCallBackJlId();
            tgChannel = apiTgChannelService.getOne(new LambdaQueryWrapper<TgChannel>()
                    .eq(TgChannel::getAppProjectId , appEventCallback.getProjectId())
                    .eq(TgChannel::getChannel, tgCallBackJlId.getChannel()));
        }else if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.CLZT.toString())){
            TgCallBackKsId tgCallBackKsId = tgCallBackIdReids.getTgCallBackKsId() ;
            tgChannel = apiTgChannelService.getOne(new LambdaQueryWrapper<TgChannel>()
                    .eq(TgChannel::getAppProjectId , appEventCallback.getProjectId())
                    .eq(TgChannel::getChannel, tgCallBackKsId.getChannel()));
        }
        if (tgChannel == null){
            printlnLog("app事件回传未查询检测链接配置",  appEventCallback);
            return;
        }
        List<TgEvent> tgEvents = tgEventService.listTgEvent(tgChannel.getTgEventId());
        if (tgEvents.size()<=0){
            printlnLog("app事件回传未查询回传事件配置",  appEventCallback);
            return;
        }
        TgEvent tgEvent = tgEvents.get(0);
        List<TgEventChild> tgEventChildren = tgEvent.getTgEventChildrens();
        TgEventChild tgEventChild = null ;

        for (TgEventChild child:tgEventChildren) {
            if (child.getTriggerNode().equals(appEventCallback.getTriggerNode())){
                tgEventChild = child;
                break;
            }
        }
        if (tgEventChild == null){
            printlnLog("app事件回传未查询子回传事件配置",  appEventCallback);
            return;
        }
        //延时回传时间
        Integer delayTimeNum = tgEventChild.getDelayTimeNum();
        if (delayTimeNum != null || delayTimeNum>0){

            //添加延时回传缓存
            TgCallBackDelayed tgCallBackDelayed = new TgCallBackDelayed();
            tgCallBackDelayed.setTriggerNode(appEventCallback.getTriggerNode());
            tgCallBackDelayed.setAppEventCallback(JSONObject.toJSONString(appEventCallback));
            tgCallBackDelayed.setPackageManageId(tgChannel.getPackageManageId());
            tgCallBackDelayed.setTgChannelId(tgChannel.getId());
            tgCallBackDelayed.setTgEventEnumsId(tgEventChild.getEventId());
            tgCallBackDelayed.setCreateTime(new Date());
            tgCallBackDelayed.setStatusType(0);
            tgCallBackDelayed.setCallbackTime(DateUtils.addDateNum(new Date() , DateUnitEnums.SECOND.getMessage(),delayTimeNum*60 ));
            tgCallBackDelayedMapper.insert(tgCallBackDelayed);
        }else {
            TgEventEnums tgEventEnums =tgEventEnumsService.getById(tgEventChild.getEventId());
            //回传用户事件是
            if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.JLYQ.toString())){
                apiTgCallBackJlIdService.callBack(appEventCallback , tgCallBackIdReids , tgEventEnums);
            }else if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.CLZT.toString())){
                apiTgCallBackKsIdService.callBack(appEventCallback , tgCallBackIdReids , tgEventEnums);
            }
        }
    }

    @Override
    public void delayCallBack() {
        int pageNum = 1;
        int pageSize = 10;
        boolean hasMore = true;
        while (hasMore) {
            Page<TgCallBackDelayed> resultPage = tgCallBackDelayedMapper.selectPage(new Page<>(pageNum, pageSize)
                    , Wrappers.<TgCallBackDelayed>lambdaQuery()
                            .eq(TgCallBackDelayed::getStatusType , 0)
                            .lt(TgCallBackDelayed::getCallbackTime , new Date()));
            List<TgCallBackDelayed> tgCallBackDelayeds =resultPage.getRecords();

            if(tgCallBackDelayeds.size() == 0)break;
            // 判断是否还有数据
            if (tgCallBackDelayeds.size() == pageSize) {
                pageNum++;
            } else {
                hasMore = false;
            }



            for (TgCallBackDelayed tgCallBackDelayed : tgCallBackDelayeds) {
                if (tgCallBackDelayed.getTriggerNode().equals(TriggerNodeEnums.AGREEMENT.toString())) {

                    JSONObject jsonObject = JSONObject.parseObject(tgCallBackDelayed.getAppEventCallback());
                    AppEventCallback appEventCallback = jsonObject.toJavaObject(AppEventCallback.class);
                    //判断用户是否解约


                    //执行延迟签约回传逻辑
                    TgCallBackIdReids tgCallBackIdReids = getUserSource(appEventCallback);
                    if (tgCallBackIdReids == null) {
                        log.info("延时回传识别为：未匹配到平台", appEventCallback);
                        return;
                    }
                    TgEventEnums tgEventEnums = tgEventEnumsService.getById(tgCallBackDelayed.getTgEventEnumsId());
                    //回传用户事件是
                    if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.JLYQ.toString())) {
                        apiTgCallBackJlIdService.callBack(appEventCallback, tgCallBackIdReids, tgEventEnums);
                    } else if (tgCallBackIdReids.getTfPlatform().equals(TfPlatformEnums.CLZT.toString())) {
                        apiTgCallBackKsIdService.callBack(appEventCallback, tgCallBackIdReids, tgEventEnums);
                    }

                } else {
                    continue;
                }
            }

        }


    }

    private void printlnLog(String msg , AppEventCallback appEventCallback){
        UserDeviceInfo userDeviceInfo = appEventCallback.getUserDeviceInfo();
        log.info("平台识别-----projectId"+appEventCallback.getProjectId()
                +"  channel: "+appEventCallback.getChannel()
                +"  triggerNode: "+appEventCallback.getTriggerNode()
                +"  userId: "+userDeviceInfo.getUserId()
                +"  ip: "+userDeviceInfo.getIp()
                +"  oaid: "+userDeviceInfo.getOaid()+msg);
    }
}

